'use client'

import { useState, useEffect } from 'react'
import { useAuth } from '@/contexts/auth-context'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { 
  ExternalLink, 
  Edit, 
  Trash2, 
  Eye, 
  EyeOff,
  Plus,
  Package
} from 'lucide-react'
import { StarDisplay } from '@/components/ui/star-rating'
import Link from 'next/link'
import { type StoredTool } from '@/lib/database'

export function MyTools() {
  const { user: authUser, loading: authLoading } = useAuth()
  const [tools, setTools] = useState<StoredTool[]>([])
  const [loading, setLoading] = useState(true)
  const [filter, setFilter] = useState<'all' | 'published' | 'pending'>('all')

  useEffect(() => {
    if (!authLoading && authUser) {
      fetchMyTools(authUser.id)
    } else if (!authLoading) {
      setLoading(false)
    }
  }, [authUser, authLoading])

  const fetchMyTools = async (userId: string) => {
    try {
      setLoading(true)
      // 使用包含用户自己工具的API
      const params = new URLSearchParams({
        userId: userId,
        includeOwn: 'true'
      })

      const response = await fetch(`/api/tools?${params.toString()}`)
      const result = await response.json()

      if (response.ok) {
        // 安全地过滤出当前用户的工具
        const toolsData = result?.data || []
        const userTools = Array.isArray(toolsData) ? toolsData.filter((tool: StoredTool) =>
          tool?.userId === userId
        ) : []
        setTools(userTools)
      }
    } catch (error) {
      console.error('获取我的工具失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const filteredTools = tools.filter(tool => {
    if (!tool) return false // 安全检查

    switch (filter) {
      case 'published':
        return tool.status === 'APPROVED' // 已审核通过即为已发布
      case 'pending':
        return tool.status === 'PENDING' || tool.status === 'REJECTED' // 待审核或被拒绝
      default:
        return true
    }
  })

  if (loading) {
    return (
      <div className="space-y-4">
        {Array.from({ length: 3 }).map((_, i) => (
          <Card key={i} className="animate-pulse">
            <CardContent className="p-6">
              <div className="h-4 bg-gray-200 rounded w-1/4 mb-2"></div>
              <div className="h-3 bg-gray-200 rounded w-3/4 mb-4"></div>
              <div className="flex gap-2">
                <div className="h-8 bg-gray-200 rounded w-20"></div>
                <div className="h-8 bg-gray-200 rounded w-20"></div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 操作栏 */}
      <div className="flex items-center justify-between">
        <div className="flex gap-4">
          <Button
            variant={filter === 'all' ? 'default' : 'outline'}
            onClick={() => setFilter('all')}
            size="sm"
          >
            全部 ({tools.length})
          </Button>
          <Button
            variant={filter === 'published' ? 'default' : 'outline'}
            onClick={() => setFilter('published')}
            size="sm"
          >
            已发布 ({tools.filter(t => t && t.status === 'APPROVED').length})
          </Button>
          <Button
            variant={filter === 'pending' ? 'default' : 'outline'}
            onClick={() => setFilter('pending')}
            size="sm"
          >
            待审核 ({tools.filter(t => t && (t.status === 'PENDING' || t.status === 'REJECTED')).length})
          </Button>
        </div>

        <Link href="/tools/new">
          <Button>
            <Plus className="h-4 w-4 mr-2" />
            发布新工具
          </Button>
        </Link>
      </div>

      {/* 工具列表 */}
      <div className="space-y-4">
        {filteredTools.length === 0 ? (
          <Card>
            <CardContent className="p-12 text-center">
              <Package className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-900 mb-2">
                {filter === 'all' ? '还没有发布任何工具' : `没有${filter === 'published' ? '已发布' : '待审核'}的工具`}
              </h3>
              <p className="text-gray-500 mb-4">
                开始分享您的第一个工具吧
              </p>
              <Link href="/tools/new">
                <Button>
                  <Plus className="h-4 w-4 mr-2" />
                  发布工具
                </Button>
              </Link>
            </CardContent>
          </Card>
        ) : (
          filteredTools.map((tool) => (
            <Card key={tool.id}>
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div>
                    <CardTitle className="flex items-center gap-2">
                      {tool.title}
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                        tool.status === 'APPROVED' && tool.isDeployed
                          ? 'bg-green-100 text-green-800' 
                          : tool.status === 'PENDING'
                          ? 'bg-yellow-100 text-yellow-800'
                          : 'bg-gray-100 text-gray-800'
                      }`}>
                        {tool.status === 'APPROVED' && tool.isDeployed ? '已发布' : 
                         tool.status === 'PENDING' ? '待审核' : '草稿'}
                      </span>
                    </CardTitle>
                    <CardDescription className="mt-1">
                      {tool.description}
                    </CardDescription>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                      {tool.category?.icon || '📦'} {tool.category?.name || '未分类'}
                    </span>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {/* 工具统计 */}
                  <div className="grid grid-cols-3 gap-4 text-sm">
                    <div className="text-center">
                      <div className="font-semibold text-gray-900">{tool._count?.reviews || 0}</div>
                      <div className="text-gray-500">评价数</div>
                    </div>
                    <div className="text-center">
                      <div className="font-semibold text-gray-900">{tool._count?.favorites || 0}</div>
                      <div className="text-gray-500">收藏数</div>
                    </div>
                    <div className="text-center">
                      <div className="flex items-center justify-center gap-1">
                        <StarDisplay rating={tool.averageRating || 0} size="sm" showValue={false} />
                        <span className="font-semibold text-gray-900">{(tool.averageRating || 0).toFixed(1)}</span>
                      </div>
                      <div className="text-gray-500">评分</div>
                    </div>
                  </div>

                  {/* 操作按钮 */}
                  <div className="flex flex-wrap gap-2">
                    {tool.status === 'APPROVED' && tool.isDeployed && (
                      <Button
                        size="sm"
                        onClick={() => window.open(`/tools/deployed/${tool.id}?pure=true`, '_blank')}
                      >
                        <ExternalLink className="h-4 w-4 mr-2" />
                        访问工具
                      </Button>
                    )}
                    
                    <Link href={`/tools/${tool.id}`}>
                      <Button size="sm" variant="outline">
                        <Eye className="h-4 w-4 mr-2" />
                        查看详情
                      </Button>
                    </Link>

                    <Link href={`/tools/${tool.id}/edit`}>
                      <Button size="sm" variant="outline">
                        <Edit className="h-4 w-4 mr-2" />
                        编辑
                      </Button>
                    </Link>

                    <Button
                      size="sm"
                      variant="outline"
                      className="text-red-600 hover:text-red-700"
                    >
                      <Trash2 className="h-4 w-4 mr-2" />
                      删除
                    </Button>
                  </div>

                  {/* 发布时间 */}
                  <div className="text-xs text-gray-500">
                    发布于 {new Date(tool.createdAt).toLocaleDateString()}
                  </div>
                </div>
              </CardContent>
            </Card>
          ))
        )}
      </div>
    </div>
  )
}
